#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from docx import Document
from docx.table import Table
import json

def analyze_docx_structure(file_path):
    """分析Word文档结构，特别关注表格信息"""
    try:
        doc = Document(file_path)
        
        result = {
            "document_info": {
                "total_paragraphs": len(doc.paragraphs),
                "total_tables": len(doc.tables)
            },
            "content_analysis": {
                "target_section_found": False,
                "target_section_index": -1,
                "tables_after_target": [],
                "total_rows_in_target_tables": 0,
                "operation_step_numbers": []
            },
            "all_headings": [],
            "table_details": []
        }
        
        # 查找所有标题和目标标题
        target_heading = "七、启动前有关厂站一、二次设备运行方式调整及状态确认（此项内容表格化）"
        target_found = False
        target_paragraph_index = -1
        
        print("=== 文档内容分析 ===")
        print(f"总段落数: {len(doc.paragraphs)}")
        print(f"总表格数: {len(doc.tables)}")
        print()
        
        # 分析所有段落，查找标题
        for i, paragraph in enumerate(doc.paragraphs):
            text = paragraph.text.strip()
            if text:
                # 检查是否是标题（包含"、"或者以数字开头）
                if ("、" in text and len(text) < 100) or (text[0].isdigit() and "、" in text):
                    result["all_headings"].append({
                        "index": i,
                        "text": text,
                        "is_target": target_heading in text
                    })
                    
                    if target_heading in text:
                        target_found = True
                        target_paragraph_index = i
                        result["content_analysis"]["target_section_found"] = True
                        result["content_analysis"]["target_section_index"] = i
                        print(f"✓ 找到目标标题 (段落 {i}): {text}")
        
        print(f"\n=== 所有标题 ===")
        for heading in result["all_headings"]:
            marker = "★" if heading["is_target"] else ""
            print(f"{marker}段落 {heading['index']:3d}: {heading['text']}")
        
        # 分析表格
        print(f"\n=== 表格详细分析 ===")
        tables_after_target = []
        
        for table_idx, table in enumerate(doc.tables):
            table_info = {
                "table_index": table_idx,
                "rows": len(table.rows),
                "columns": len(table.columns) if table.rows else 0,
                "headers": [],
                "sample_data": [],
                "contains_operation_steps": False,
                "operation_step_range": []
            }
            
            # 提取表格头部信息
            if table.rows:
                header_row = table.rows[0]
                for cell in header_row.cells:
                    cell_text = cell.text.strip()
                    table_info["headers"].append(cell_text)
                
                # 提取前几行数据作为样本
                sample_rows = min(5, len(table.rows))
                for row_idx in range(1, sample_rows):  # 跳过表头
                    if row_idx < len(table.rows):
                        row_data = []
                        for cell in table.rows[row_idx].cells:
                            row_data.append(cell.text.strip())
                        table_info["sample_data"].append(row_data)
                
                # 检查是否包含操作步骤（查找序号列）
                step_numbers = []
                for row_idx in range(1, len(table.rows)):
                    if row_idx < len(table.rows) and table.rows[row_idx].cells:
                        first_cell = table.rows[row_idx].cells[0].text.strip()
                        # 尝试提取数字序号
                        if first_cell.isdigit():
                            step_numbers.append(int(first_cell))
                        elif first_cell and first_cell[0].isdigit():
                            # 提取开头的数字
                            num_str = ""
                            for char in first_cell:
                                if char.isdigit():
                                    num_str += char
                                else:
                                    break
                            if num_str:
                                step_numbers.append(int(num_str))
                
                if step_numbers:
                    table_info["contains_operation_steps"] = True
                    table_info["operation_step_range"] = [min(step_numbers), max(step_numbers)]
                    result["content_analysis"]["operation_step_numbers"].extend(step_numbers)
            
            result["table_details"].append(table_info)
            
            print(f"\n表格 {table_idx + 1}:")
            print(f"  行数: {table_info['rows']}")
            print(f"  列数: {table_info['columns']}")
            print(f"  表头: {table_info['headers']}")
            print(f"  包含操作步骤: {table_info['contains_operation_steps']}")
            if table_info['contains_operation_steps']:
                print(f"  步骤序号范围: {table_info['operation_step_range']}")
            
            # 如果目标标题已找到，记录其后的表格
            if target_found:
                tables_after_target.append(table_info)
        
        # 统计目标标题后的表格信息
        if target_found and tables_after_target:
            result["content_analysis"]["tables_after_target"] = tables_after_target
            total_rows = sum(t["rows"] for t in tables_after_target)
            result["content_analysis"]["total_rows_in_target_tables"] = total_rows
            
            print(f"\n=== 目标标题后的表格统计 ===")
            print(f"表格数量: {len(tables_after_target)}")
            for i, table_info in enumerate(tables_after_target):
                print(f"  表格 {i+1}: {table_info['rows']} 行")
            print(f"总行数: {total_rows}")
            
            # 验证是否符合 23+33+203=259 的模式
            if len(tables_after_target) >= 3:
                first_three_rows = [t["rows"] for t in tables_after_target[:3]]
                print(f"前三个表格行数: {first_three_rows}")
                if first_three_rows == [23, 33, 203]:
                    print("✓ 符合预期的 23+33+203=259 行数模式")
                else:
                    print(f"× 不符合预期模式，期望[23, 33, 203]，实际{first_three_rows}")
        
        # 操作步骤序号统计
        if result["content_analysis"]["operation_step_numbers"]:
            all_steps = result["content_analysis"]["operation_step_numbers"]
            print(f"\n=== 操作步骤序号统计 ===")
            print(f"总步骤数: {len(all_steps)}")
            print(f"序号范围: {min(all_steps)} - {max(all_steps)}")
            print(f"是否连续: {list(range(min(all_steps), max(all_steps)+1)) == sorted(set(all_steps))}")
        
        return result
        
    except Exception as e:
        print(f"分析文档时出错: {str(e)}")
        return {"error": str(e)}

if __name__ == "__main__":
    file_path = "E:/java_projects/ai-doc-portal/test-results/附件2.110kV宝嘉变电站及110kV莲宝线1S1启动方案（例子）.docx"
    
    print("开始分析Word文档...")
    result = analyze_docx_structure(file_path)
    
    # 保存结果到JSON文件
    output_file = "E:/java_projects/ai-doc-portal/test-results/docx_analysis_result.json"
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(result, f, ensure_ascii=False, indent=2)
    
    print(f"\n分析完成，详细结果已保存到: {output_file}")